/*websocket服务器搭建*/
#include <iostream>
#include <websocketpp/config/asio_no_tls.hpp>

#include <websocketpp/server.hpp>
using std::cout;
using std::endl;
typedef websocketpp::server<websocketpp::config::asio> wsserver_t;

void http_callback(wsserver_t* srv,websocketpp::connection_hdl hd1)
{
    //获取服务端通信连接对象---获取connection_hdl 对应连接的connection_ptr
    wsserver_t::connection_ptr conn=srv->get_con_from_hdl(hd1);
    //获取请求正文
    std::cout<<"body"<<conn->get_request_body()<<endl;
    //获取http请求对象
    websocketpp::http::parser::request req=conn->get_request();
    //输出请求方法和uri
    cout<<"method: "<<req.get_method()<<endl;
    cout<<"uri: "<<req.get_uri()<<endl;

    std::string body="<html><body><h1>HTTP_callback</h1></body></html>";
    //设置响应信息
    conn->set_body(body);
    conn->append_header("Content-Type","text/html");
    conn->set_status(websocketpp::http::status_code::ok);

}
void wsopen_callback(wsserver_t* srv,websocketpp::connection_hdl hd1)
{
    cout<<"wensocket握手成功"<<endl;
}
void wsclose_callback(wsserver_t* srv,websocketpp::connection_hdl hd1)
{
    cout<<"wensocket断开成功"<<endl;
}
void wsmsg_callback(wsserver_t* srv,websocketpp::connection_hdl hd1,wsserver_t::message_ptr msg)
{
    wsserver_t::connection_ptr conn=srv->get_con_from_hdl(hd1);
    //获取websocket中payload数据
    cout<<"wsmsg: "<<msg->get_payload()<<endl;
    std::string rsp="client say: "+msg->get_payload();
    //发送数据
    conn->send(rsp,websocketpp::frame::opcode::text);
}


int main()
{
    // 1.实例化Server对象
    wsserver_t wssrv;
    // 2.设置日志等级
    wssrv.set_access_channels(websocketpp::log::alevel::none);
    // 3.初始化asio调度器
    wssrv.init_asio();
    // 3.1设置定制重用
    wssrv.set_reuse_addr(true);
    // 4.设置回调函数
    wssrv.set_http_handler(std::bind(http_callback,&wssrv,std::placeholders::_1)); /*http请求回调处理函数*/
    wssrv.set_open_handler(std::bind(wsopen_callback,&wssrv,std::placeholders::_1));/*websocket握⼿成功回调处理函数*/
    wssrv.set_close_handler(std::bind(wsclose_callback,&wssrv,std::placeholders::_1));/*websocket连接关闭回调处理函数*/
    wssrv.set_message_handler(std::bind(wsmsg_callback,&wssrv,std::placeholders::_1,std::placeholders::_2)); /*websocket消息回调处理函数*/

    //5.设置监听窗口
    wssrv.listen(8085);
    //6.开始获取新连接
    wssrv.start_accept();
    //7.启动服务器
    wssrv.run();
    return 0;
}